<script setup lang="ts">
import { ref, reactive, h, watch } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import {
  ElMessage,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElInput,
  ElCard,
} from "element-plus";
import { getResultList, getResultDetail } from "../servers";

const props = defineProps<{
  taskId: string;
  visible: boolean;
}>();

const emit = defineEmits<{
  close: [];
}>();

const loading = ref(false);
const resultList = ref<any[]>([]);
const resultStatistics = ref<any>(null);
const showDetailDialog = ref(false);
const resultDetail = ref<any>(null);
const loadingDetail = ref(false);
const detectionResult = ref<any>(null);

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const getSeverityTag = (severity: string) => {
  const severityMap: Record<string, any> = {
    critical: { text: "严重", type: "danger" },
    high: { text: "高危", type: "danger" },
    medium: { text: "中危", type: "warning" },
    low: { text: "低危", type: "info" },
  };
  return severityMap[severity] || { text: severity, type: "info" };
};

const columns = ref<TableColumn[]>([
  {
    label: "场景名称",
    prop: "scenario_name",
    minWidth: 200,
    show: true,
    render: (row) => {
      return h("span", {}, row.scenario?.scenario_name || "-");
    },
  },
  {
    label: "场景编码",
    prop: "scenario_code",
    minWidth: 200,
    show: true,
    render: (row) => {
      return h("span", {}, row.scenario?.scenario_code || "-");
    },
  },
  {
    label: "严重程度",
    prop: "severity",
    width: 120,
    show: true,
    render: (row) => {
      const severityInfo = getSeverityTag(row.scenario?.severity);
      return h(
        ElTag,
        { type: severityInfo.type, size: "small" },
        () => severityInfo.text
      );
    },
  },
  {
    label: "检测结果",
    prop: "is_vulnerable",
    width: 120,
    show: true,
    render: (row) => {
      return h(
        ElTag,
        {
          type: row.is_vulnerable ? "danger" : "success",
          size: "small",
        },
        () => (row.is_vulnerable ? "发现漏洞" : "安全")
      );
    },
  },
  {
    label: "响应状态码",
    prop: "response_status_code",
    width: 120,
    show: true,
    render: (row) => {
      const status = row.response_status_code;
      if (!status) return h("span", {}, "-");
      const color =
        status >= 200 && status < 300
          ? "success"
          : status >= 400
          ? "danger"
          : "warning";
      return h(ElTag, { type: color, size: "small" }, status);
    },
  },
  {
    label: "响应时间",
    prop: "response_time",
    width: 100,
    show: true,
    render: (row) => {
      const time = row.response_time || 0;
      return h("span", {}, `${time}ms`);
    },
  },
  {
    label: "检测时间",
    prop: "created_at",
    width: 180,
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 100,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

const fetchResultList = async () => {
  if (!props.taskId) return;

  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      task_id: props.taskId,
    };
    const { data } = await getResultList(params);
    resultList.value = data?.results || [];
    resultStatistics.value = {
      total: data?.total || 0,
      vulnerable_count:
        data?.results?.filter((r: any) => r.is_vulnerable).length || 0,
      safe_count:
        data?.results?.filter((r: any) => !r.is_vulnerable).length || 0,
      detection_rate: data?.total
        ? (data?.results?.filter((r: any) => r.is_vulnerable).length || 0) /
          data.total
        : 0,
    };
    pagination.total = data?.total || 0;
  } catch (error) {
    ElMessage.error("获取结果列表失败");
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchResultList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchResultList();
};

// 解析防护状态配置
const getProtectionStatusConfig = (status: string) => {
  const statusConfig: Record<string, any> = {
    blocked: {
      icon: "🛡️",
      text: "防护有效",
      badge: "success",
      color: "#52c41a",
    },
    bypassed: {
      icon: "🔴",
      text: "防护失效（存在漏洞）",
      badge: "danger",
      color: "#ff4d4f",
    },
    failed: {
      icon: "⚠️",
      text: "防护失效",
      badge: "warning",
      color: "#faad14",
    },
    unknown: {
      icon: "❓",
      text: "无法判断",
      badge: "info",
      color: "#1890ff",
    },
    error: {
      icon: "❌",
      text: "测试异常",
      badge: "info",
      color: "#d9d9d9",
    },
  };
  return statusConfig[status] || statusConfig.unknown;
};

// 获取风险等级标签类型
const getRiskLevelTag = (riskLevel: string) => {
  const riskConfig: Record<string, any> = {
    safe: { text: "安全", type: "success" },
    warning: { text: "警告", type: "warning" },
    critical: { text: "严重", type: "danger" },
    info: { text: "信息", type: "info" },
  };
  return riskConfig[riskLevel] || { text: riskLevel, type: "info" };
};

const handleViewDetail = async (row: any) => {
  loadingDetail.value = true;
  try {
    const { data } = await getResultDetail({ result_id: row.result_id });
    resultDetail.value = data;

    // 解析 detection_result JSON 字符串获取防护有效性数据
    if (data?.detection_result) {
      try {
        const parsed = JSON.parse(data.detection_result);
        // 合并接口直接返回的字段和解析的字段
        detectionResult.value = {
          protection_status: data.protection_status || parsed.protection_status,
          protection_description:
            data.protection_description || parsed.protection_description,
          baseline_status: data.baseline_status || parsed.baseline_status,
          attack_status: data.attack_status || parsed.attack_status,
          response_diff_score:
            data.response_diff_score || parsed.response_diff_score,
          risk_level: data.risk_level || parsed.risk_level,
          recommendation: data.recommendation || parsed.recommendation,
          detected_signs: data.detected_signs || parsed.detected_signs || [],
          blocked_indicators:
            data.blocked_indicators || parsed.blocked_indicators || [],
          // 从 detection_result 中解析的字段
          is_vulnerable: parsed.is_vulnerable,
          waf_detected: parsed.waf_detected,
          waf_type: parsed.waf_type,
        };
      } catch (e) {
        console.error("解析 detection_result 失败:", e);
        detectionResult.value = null;
      }
    } else if (data) {
      // 如果没有 detection_result，尝试从接口直接返回的字段获取
      detectionResult.value = {
        protection_status: data.protection_status,
        protection_description: data.protection_description,
        baseline_status: data.baseline_status,
        attack_status: data.attack_status,
        response_diff_score: data.response_diff_score,
        risk_level: data.risk_level,
        recommendation: data.recommendation,
        detected_signs: data.detected_signs || [],
        blocked_indicators: data.blocked_indicators || [],
      };
    } else {
      detectionResult.value = null;
    }

    showDetailDialog.value = true;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取结果详情失败");
  } finally {
    loadingDetail.value = false;
  }
};

const handleClose = () => {
  emit("close");
};

// 监听visible变化，当对话框打开时获取数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.taskId) {
      pagination.currentPage = 1;
      fetchResultList();
    }
  }
);
</script>

<template>
  <el-dialog
    :model-value="visible"
    title="任务结果"
    width="1400px"
    @close="handleClose"
  >
    <!-- 统计信息 -->
    <div v-if="resultStatistics" style="margin-bottom: 20px">
      <el-card>
        <div style="display: flex; gap: 20px; align-items: center">
          <div>
            <span style="font-size: 14px; color: #666">总测试：</span>
            <span style="font-size: 16px; font-weight: bold">{{
              resultStatistics.total || 0
            }}</span>
          </div>
          <div>
            <span style="font-size: 14px; color: #666">发现漏洞：</span>
            <span style="font-size: 16px; font-weight: bold; color: #f56c6c">{{
              resultStatistics.vulnerable_count || 0
            }}</span>
          </div>
          <div>
            <span style="font-size: 14px; color: #666">安全通过：</span>
            <span style="font-size: 16px; font-weight: bold; color: #67c23a">{{
              resultStatistics.safe_count || 0
            }}</span>
          </div>
          <div>
            <span style="font-size: 14px; color: #666">检测率：</span>
            <span style="font-size: 16px; font-weight: bold"
              >{{
                ((resultStatistics.detection_rate || 0) * 100).toFixed(1)
              }}%</span
            >
          </div>
        </div>
      </el-card>
    </div>

    <DynamicTable
      :columns="columns"
      :data="resultList"
      :loading="loading"
      :pagination="pagination"
      @current-page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
      <template #action="{ row }">
        <el-button type="primary" size="small" @click="handleViewDetail(row)">
          详情
        </el-button>
      </template>
    </DynamicTable>

    <!-- 结果详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="结果详情" width="1000px">
      <div v-loading="loadingDetail">
        <el-descriptions
          v-if="resultDetail"
          :column="2"
          border
          style="margin-bottom: 20px"
        >
          <el-descriptions-item label="结果ID">{{
            resultDetail.result_id
          }}</el-descriptions-item>
          <el-descriptions-item label="场景名称">{{
            resultDetail.scenario?.scenario_name
          }}</el-descriptions-item>
          <el-descriptions-item label="场景编码">{{
            resultDetail.scenario?.scenario_code
          }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag
              :type="getSeverityTag(resultDetail.scenario?.severity).type"
            >
              {{ getSeverityTag(resultDetail.scenario?.severity).text }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="检测结果">
            <el-tag :type="resultDetail.is_vulnerable ? 'danger' : 'success'">
              {{ resultDetail.is_vulnerable ? "发现漏洞" : "安全" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="响应状态码">{{
            resultDetail.response_status_code || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="响应时间"
            >{{ resultDetail.response_time || 0 }}ms</el-descriptions-item
          >
          <el-descriptions-item label="检测时间">{{
            resultDetail.created_at
          }}</el-descriptions-item>
          <el-descriptions-item label="DNSLog验证">
            <el-tag :type="resultDetail.dnslog_verified ? 'success' : 'info'">
              {{ resultDetail.dnslog_verified ? "已验证" : "未验证" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="错误信息" :span="2">
            {{ resultDetail.error_message || "无" }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 防护有效性展示 -->
        <el-card
          v-if="
            detectionResult &&
            (detectionResult.protection_status ||
              detectionResult.waf_detected !== undefined ||
              detectionResult.detected_signs?.length)
          "
          class="protection-card"
        >
          <template #header>
            <div class="protection-header">
              <span class="status-icon">{{
                getProtectionStatusConfig(
                  detectionResult.protection_status ||
                    (detectionResult.waf_detected
                      ? "blocked"
                      : detectionResult.is_vulnerable
                      ? "bypassed"
                      : "unknown")
                ).icon
              }}</span>
              <h4 class="status-text">
                {{
                  getProtectionStatusConfig(
                    detectionResult.protection_status ||
                      (detectionResult.waf_detected
                        ? "blocked"
                        : detectionResult.is_vulnerable
                        ? "bypassed"
                        : "unknown")
                  ).text
                }}
              </h4>
              <el-tag
                :type="
                  getProtectionStatusConfig(
                    detectionResult.protection_status || 
                    (detectionResult.waf_detected ? 'blocked' : detectionResult.is_vulnerable ? 'bypassed' : 'unknown')
                  ).badge as any
                "
                size="small"
              >
                {{
                  detectionResult.protection_status ||
                  (detectionResult.waf_detected
                    ? "blocked"
                    : detectionResult.is_vulnerable
                    ? "bypassed"
                    : "unknown")
                }}
              </el-tag>
            </div>
          </template>

          <!-- 防护描述 -->
          <div
            v-if="detectionResult.protection_description"
            class="protection-description"
          >
            {{ detectionResult.protection_description }}
          </div>

          <!-- WAF信息 -->
          <div
            v-if="detectionResult.waf_detected !== undefined"
            class="waf-info-section"
          >
            <div class="waf-item">
              <label>WAF检测:</label>
              <el-tag
                :type="detectionResult.waf_detected ? 'success' : 'info'"
                size="small"
              >
                {{
                  detectionResult.waf_detected ? "已检测到WAF" : "未检测到WAF"
                }}
              </el-tag>
            </div>
            <div v-if="detectionResult.waf_type" class="waf-item">
              <label>WAF类型:</label>
              <span>{{ detectionResult.waf_type }}</span>
            </div>
          </div>

          <!-- 对比信息 -->
          <div class="comparison-section">
            <div class="comparison-item">
              <label>基线状态码:</label>
              <span>{{ detectionResult.baseline_status || "-" }}</span>
            </div>
            <div class="comparison-item">
              <label>攻击状态码:</label>
              <span>{{ detectionResult.attack_status || "-" }}</span>
            </div>
            <div class="comparison-item">
              <label>响应差异度:</label>
              <span>{{
                detectionResult.response_diff_score
                  ? `${(detectionResult.response_diff_score * 100).toFixed(1)}%`
                  : "-"
              }}</span>
            </div>
          </div>

          <!-- 风险等级 -->
          <div v-if="detectionResult.risk_level" class="risk-level-section">
            <label>风险等级:</label>
            <el-tag
              :type="getRiskLevelTag(detectionResult.risk_level).type"
              size="small"
            >
              {{ getRiskLevelTag(detectionResult.risk_level).text }}
            </el-tag>
          </div>

          <!-- 建议措施 -->
          <div
            v-if="detectionResult.recommendation"
            class="recommendation-section"
          >
            <label>建议:</label>
            <p>{{ detectionResult.recommendation }}</p>
          </div>

          <!-- 漏洞特征 -->
          <div
            v-if="
              detectionResult.detected_signs &&
              detectionResult.detected_signs.length > 0
            "
            class="vulnerability-signs-section"
          >
            <label>检测到的漏洞特征:</label>
            <ul>
              <li
                v-for="(sign, index) in detectionResult.detected_signs"
                :key="index"
              >
                {{ sign }}
              </li>
            </ul>
          </div>

          <!-- 拦截特征 -->
          <div
            v-if="
              detectionResult.blocked_indicators &&
              detectionResult.blocked_indicators.length > 0
            "
            class="blocked-indicators-section"
          >
            <label>拦截特征:</label>
            <ul>
              <li
                v-for="(indicator, index) in detectionResult.blocked_indicators"
                :key="index"
              >
                {{ indicator }}
              </li>
            </ul>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<style scoped lang="scss">
.protection-card {
  margin-top: 20px;
}

.protection-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-icon {
  font-size: 24px;
}

.status-text {
  margin: 0;
  flex: 1;
  font-size: 16px;
  font-weight: 500;
}

.protection-description {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  color: #333;
  line-height: 1.6;
}

.waf-info-section {
  margin: 16px 0;
  padding: 12px;
  background: #f0f9ff;
  border-left: 3px solid #1890ff;
  border-radius: 4px;
  display: flex;
  gap: 20px;
  flex-wrap: wrap;

  .waf-item {
    display: flex;
    align-items: center;
    gap: 8px;

    label {
      font-weight: 500;
      color: #666;
    }
  }
}

.comparison-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin: 16px 0;
}

.comparison-item {
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;

  label {
    display: block;
    font-size: 12px;
    color: #8c8c8c;
    margin-bottom: 4px;
  }

  span {
    font-size: 16px;
    font-weight: 500;
    color: #262626;
  }
}

.risk-level-section {
  margin: 16px 0;
  display: flex;
  align-items: center;
  gap: 8px;

  label {
    font-weight: 500;
    color: #666;
  }
}

.recommendation-section {
  margin-top: 16px;
  padding: 12px;
  background: #f6ffed;
  border-left: 3px solid #52c41a;
  border-radius: 4px;

  label {
    font-weight: 500;
    margin-bottom: 8px;
    display: block;
    color: #333;
  }

  p {
    margin: 0;
    color: #262626;
    line-height: 1.6;
  }
}

.vulnerability-signs-section {
  margin-top: 16px;
  padding: 12px;
  background: #fff2f0;
  border-left: 3px solid #ff4d4f;
  border-radius: 4px;

  label {
    font-weight: 500;
    margin-bottom: 8px;
    display: block;
    color: #333;
  }

  ul {
    margin: 0;
    padding-left: 20px;
    color: #262626;

    li {
      margin: 4px 0;
      line-height: 1.6;
    }
  }
}

.blocked-indicators-section {
  margin-top: 16px;
  padding: 12px;
  background: #f6ffed;
  border-left: 3px solid #52c41a;
  border-radius: 4px;

  label {
    font-weight: 500;
    margin-bottom: 8px;
    display: block;
    color: #333;
  }

  ul {
    margin: 0;
    padding-left: 20px;
    color: #262626;

    li {
      margin: 4px 0;
      line-height: 1.6;
    }
  }
}
</style>
